package com.datviet.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.datviet.entity.Post;
import com.datviet.service.IPostService;

@Controller
@RequestMapping(value = "public/post")
public class PostController {

	@Autowired
	private IPostService postService;
	
	@RequestMapping( value = {"/"}, method = RequestMethod.GET)
	public String postPage(Model model) {
		String[] searchingKeyword = (String[])model.asMap().get("searchingKeyword");
		if(searchingKeyword == null)
			searchingKeyword = new String[0];
		List<Post> posts = postService.findLastedPost(searchingKeyword);
		StringBuilder stringBuilder = new StringBuilder();
		for(int i = 0; i < searchingKeyword.length; i++){
			if(i == 0){
				stringBuilder.append(searchingKeyword[i]);
			} else {
				stringBuilder.append("," + searchingKeyword[i]);
			}
		}
		model.addAttribute("searchingKeyword", stringBuilder.toString());
		model.addAttribute("posts", posts);
		return "public.posts";
	}
	
	@RequestMapping( value = "/search/", method = RequestMethod.POST)
	public String searchPost(Model model,RedirectAttributes redirectAttributes, @RequestParam(value = "searchingKeyword") String... searchingKeyword) {
		redirectAttributes.addFlashAttribute("searchingKeyword", searchingKeyword);
		return "redirect:/app/public/post/";
	}	
	
	@RequestMapping( value = {"/refresh/", "/refresh"}, method = RequestMethod.POST)
	@ResponseBody
	public List<Post> refreshPost(@RequestParam(value = "searchingKeyword") String... searchingKeyword) {
		List<Post> posts = postService.findLastedPost(searchingKeyword);
		return posts;
	}	
}
